<script setup lang="ts">
import {
  addRolePark,
  getAllFunction,
  getRoleDetail,
  updateRolePark,
} from "@/api/system";
import { type addRoleParams, type RoleALLTree } from "@/types/system";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import type { TreeInstance } from "element-plus/lib/components/index.js";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
const Params = ref<addRoleParams>({
  remark: "",
  roleName: "",
  perms: [],
  roleId: undefined,
  userTotal: undefined,
});
const active = ref(1);
const RoleRules = ref<FormRules>({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  remark: [{ required: false, message: "请输入角色描述", trigger: "blur" }],
  Array: [{ required: true, message: "请选择权限", trigger: "change" }],
});
const roleRef = ref<FormInstance>();
const treeList = ref<RoleALLTree[]>([]);
// 第三步
const TreeRefs = ref<TreeInstance[]>();
const data = async () => {
  const res = await getAllFunction();
  treeList.value = res.data;
};
const getDetail = async (id: number) => {
  const res = await getRoleDetail(id);
  Params.value.perms = res.data.perms;
  Params.value.roleName = res.data.roleName;
  Params.value.remark = res.data.remark;
  Params.value.roleId = res.data.roleId;
  // Params.value.userTotal = res.data.userTotal;
  // console.log('res',res);
};
const route = useRoute();
onMounted(() => {
  data();
  if (route.params.id) {
    const id = Number(route.params.id);
    getDetail(id);
  }
});
const treeRefs = ref<TreeInstance[]>();
const next = async () => {
    if (active.value === 1) {
    await roleRef.value?.validateField("roleName");
    active.value++;
  } else if (active.value === 2) {
    Params.value.perms = [];
    treeRefs.value?.forEach((item) => {
      const keys=item.getCheckedKeys() as number[]
      Params.value.perms.push(keys);
      console.log('item',keys);
    });
    if (Params.value.perms.flat().length === 0) {
      ElMessage.error("请选择权限");
    } else {
      active.value++;
      TreeRefs.value?.forEach((tree,index)=>{
        tree.setCheckedKeys(Params.value.perms[index])
      })
    }
  }
};

const router = useRouter();
const submit = async () => {
  Params.value.perms = Array.from(new Set(Params.value.perms));
  if (route.params.id) {
   const res= await updateRolePark(Params.value);
    if(res.code===10000){
    ElMessage.success("编辑成功");
    router.back();
    }
  } else {
    const res = await addRolePark(Params.value);
    console.log("okkkkres", res);
    if(res.code===10000){
    ElMessage.success("添加成功");
    router.back();
    }
  }
};
</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header
        v-if="$route.params.id"
        content="编辑角色"
        @back="$router.back()"
      />
      <el-page-header v-else content="添加角色" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="active">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div class="form-container" v-show="active === 1">
        <div class="title">角色信息</div>
        <div class="forma" style="width: 500px; margin-left: 200px">
          <el-form
            :inline="false"
            :model="Params"
            :rules="RoleRules"
            ref="roleRef"
          >
            <el-form-item label="角色名称:" prop="roleName">
              <el-input
                v-model="Params.roleName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色描述:" prop="remark">
              <el-input
                v-model="Params.remark"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container" v-show="active === 2">
        <div class="title">权限配置</div>
        <div class="tree-table">
          <div
            class="tree-item"
            v-for="(item, index) in treeList"
            :key="item.id"
          >
            <div class="tree-title">{{ item.title }}</div>
            <div class="tree-wrapper">
              <el-tree
                style="max-width: 600px"
                :data="item.children"
                show-checkbox
                node-key="id"
                highlight-current
                :props="{ label: 'title' }"
                :default-checked-keys="Params.perms[index]"
                default-expand-all
                ref="treeRefs"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="form-container" v-show="active === 3">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">
              <div class="label">角色名称:</div>
              <div class="value">{{ Params.roleName }}</div>
            </div>
            <div class="form-item">
              <div class="label">角色描述:</div>
              <div class="value">{{ Params.remark }}</div>
            </div>
            <div class="form-item">
              <div class="tree-table">
                <div
                  class="tree-item"
                  v-for="(item, index) in treeList"
                  :key="item.id"
                >
                  <div class="tree-title">{{ item.title }}</div>
                  <div class="tree-wrapper">
                    <el-tree
                      style="max-width: 600px"
                      :data="item.children"
                      show-checkbox
                      node-key="id"
                      :props="{ label: 'title', disabled: () => true }"
                      :default-checked-keys="Params.perms[index]"
                      default-expand-all
                      ref="TreeRefs"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="active--" v-if="active !== 1">上一步</el-button>
        <el-button type="primary" @click="next" v-if="active !== 3"
          >下一步</el-button
        >
        <el-button type="primary" v-if="active === 3" @click="submit"
          >确认添加</el-button
        >

      {{Params.perms}}
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-table {
    display: flex;
    justify-content: space-between;
    padding: 50px;

    .tree-item {
      flex: 1;
      border-right: 1px solid #e4e7ec;
      padding: 0px 4px;
      text-align: center;
      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
